<?php
	include('API.php');
?>
<?php
	
	/* 通过 set 的 date_update 比对 set 的修改情况;
	 * 对于新增 或 修改 的 set 返回true;
	 * 对于无变更的 set 返回 false;
	 * @param SET set
	 * @return Boolean
	*/
	function compareSet($set){
		global $wpdb;
		
		
		$sql = "select date_update from flickr_sets where id=".$set['id']."";
		$queryResult = $wpdb->get_row($sql);
		if(mysql_error() != ""){
			fsLog("<b>MYSQL ERROR: ".mysql_error()."</b>", "error");
			return false;
		}else{
			if($queryResult === null){
				//新增的 set
				fsLog("SET 比对结果 : 新增","success");
				return true;
			}else{
				$dateUpdateBefore = $set['date_update'];
				$dateUpdateNow = strtotime($queryResult->date_update);
				
				if($dateUpdateBefore == $dateUpdateNow){
					// set 无变更
					fsLog("SET 比对结果 : 无变更, continue","success");
					return false;
				}else{
					// set 有变更
					fsLog("SET 比对结果 : 有变更","success");
					return true;
				}
			}
		}
		
		
		
		
		
		
		
		
	}


	function syncSets(){
		global $wpdb;
		
		fsLog("===============================同步 Sets===============================","error",true);

		$photoSetsList = callAPI(array(
			method => 'flickr.photosets.getList',
		));
		
		
		if ($photoSetsList != false){

			//resetSetTables();
			
			$setsSaver = array();
			$changedSetsSaver = array();
			
			fsLog("-------------------------------------开始 -------------------------------------","warn",true);
			//insert 条数计数器
			$insertCounter = 0;
			foreach ($photoSetsList['photosets']['photoset'] as $set){
				fsLog("***** SET ：(".$set['id'].") ".$set['title']['_content']."：","warn",true);
				array_push($setsSaver,$set['id']);
				
				
				/** 查询 set 的更新情况 **/
				$compareResult = compareSet($set);
				if($compareResult === true){
					
					
					/** 对于新增与修改的记录， 插入到  flickr_sets 表**/
					$insertSetResult = insertSet($set);
					if($insertSetResult['state'] == false){
						fsLog("flickr_sets 操作失败", "error", true);
					}else{
						fsLog("flickr_sets 操作成功", "success");
					}
					/** 对于新增与修改的记录， 插入到  flickr_sets 表**/
					
					
					
					/** 对于新增与修改的记录，插入数据到  wp_posts 表**/
					$insertPostsResult = insertPost($set);				
					if($insertPostsResult['state'] == false){
						fsLog("wp_posts 操作失败", "error", true);
					}else{
						fsLog("wp_posts 操作成功", "success");
					}
					/** 对于新增与修改的记录，插入数据到  wp_posts 表**/
					
					
					
					/** 如果wp_posts写入成功 ， 插入数据到  wp_postmeta 表**/
					if($insertPostsResult['state'] && is_array($insertPostsResult['insertPostInfo'])){
						$insertMetaResult = insertMeta($insertPostsResult['insertPostInfo']['set_id'],$insertPostsResult['insertPostInfo']['post_id']);	
						if($insertMetaResult['state'] == false){
							fsLog("wp_postmeta 操作失败", "error", true);
						}else{
							fsLog("wp_postmeta 操作成功", "success");
						}
					}elseif($insertPostsResult['state']){
						$insertMetaResult['state'] = true;
						fsLog("wp_postmeta 操作成功，无变更", "success");
					}
					/** 如果wp_posts写入成功 ， 插入数据到  wp_postmeta 表 End **/
					
					
					
					/** 对于新增与修改的记录，删除相关的 photo , 记录到$changedSetsSaver中**/
					$deleteResult = deletePhotosBySetId($set['id']);
					if($deleteResult['state']){
						array_push($changedSetsSaver,$set);
					}
					
					/** 对于新增与修改的记录，同步 photo **/
					
					/*
					if($insertSetResult['state'] && $insertPostsResult['state'] && $insertMetaResult['state']){
						$insertCounter++;
						fsLog("同步成功", "success", true);
					}
					*/
					
				}else{
					
				}
			}
			fsLog("-------------------------------------结束-------------------------------------","warn",true);
			//if($insertCounter == 0){
			//	fsLog("SETS 同步失败", "error");
			//}else{
				fsLog("SETS 同步成功：共有 ".$insertCounter." 条入库", "success",true);
				
				//从 wp_posts 和 wp_postmeta中 删除已经从 flickr 中移除的 set
				selectDeleted($setsSaver);

				beginSyncPhotos($changedSetsSaver);
			//}


		}
	}

	function deletePhotosBySetId($setId){
		global $wpdb;
		$result = array();
		
		$sql = "delete from `flickr_photos` WHERE `set_id`=".$setId;
		$deleteResult = $wpdb->query($sql);
		if(mysql_error() != ""){
			fsLog("<b>MYSQL ERROR: ".mysql_error()."</b>", "error");
			$result['state'] = false;
		}else{
			fsLog("与该 SET 相关的 <b>".$deleteResult."</b> 张照片从 flickr_photos 中删除", "success");
			$result['state'] = true;
			$result['counter'] = $deleteResult;
		}
		
		return $result;
	}


	function beginSyncPhotos($sets){
		global $wpdb;
		fsLog("===============================同步 Photos===============================","error",true);
		
		//初始化 flickr_photos
		//resetPhotoTables();
		
		foreach($sets as $set){
			$setId = $set['id'];
			$photoSetsList = callAPI(array(
				method => 'flickr.photosets.getPhotos',
				extras => 'date_taken,original_format,url_o',
				photoset_id => $setId
			));
			
			if ($photoSetsList != false){
				$insertCounter = insertPhoto($photoSetsList['photoset']['photo'],$photoSetsList['photoset']['id']);
				if($insertCounter != false){
					fsLog("PHOTOS 同步成功：从 ".$photoSetsList['photoset']['id']." 导入图片 ".$insertCounter." 张", "success",true);
				}else{
					fsLog("PHOTOS 同步失败", "error");
				}
			}
			
		}
		
	}

	function insertPhoto($photos,$setId){
		//插入所有图片
		global $wpdb;
		$counter = 0;
		foreach($photos as $photo){
			$insertArray = array(
				'id' => $photo['id'],
				'secret' => $photo['secret'],
				'server' => $photo['server'],
				'farm' => $photo['farm'],
				'title' => $photo['title'],
				'isprimary' => $photo['isprimary'],
				'date_taken' => $photo['datetaken'],
				'set_id' => $setId,
				'secret_o'=>$photo['originalsecret'],
				'format_o'=>$photo['originalformat'],
				'url_o'=>$photo['url_o'],
				'height_o'=>$photo['height_o'],
				'width_o'=>$photo['width_o']
			);
			
			$insertResult = $wpdb->insert('flickr_photos',$insertArray);
			if($insertResult != false){
				$counter++;
			}else{
				fsLog("<b>MYSQL ERROR: ".mysql_error()."</b> --- SET ID: ".$setId. " PHOTO ID: ".$photo['id'], "error");
			}	
		}
		if($counter != 0){
			return $counter;
		}else{
			return false;
		}
	}

	function resetPhotoTables(){
		global $wpdb;
		
		fsLog("-------------------------------------初始化开始-------------------------------------","warn",true);
		
		//empty flickr_sets
		$wpdb->query("truncate table flickr_photos");
		if(mysql_error() != ""){
			fsLog("<b>MYSQL ERROR: ".mysql_error()."</b>", "error");
			return false;
		}else{
			fsLog("flickr_photos 已清空...","success");
			fsLog("-------------------------------------初始化结束-------------------------------------","warn",true);
			return true;
		}
		
		
	}


	
	//insert record into flickr_sets
	function insertSet($sets){
		global $wpdb;
		
		$insertArray = array(
			'id' => $sets['id'],
			'primary' => $sets['primary'],
			'secret' => $sets['secret'],
			'server' => $sets['server'],
			'farm' => $sets['farm'],
			'photos' => $sets['photos'],
			'title' => $sets['title']['_content'],
			'description' => $sets['description']['_content'],
			'needs_interstitial' => $sets['needs_interstitial'],
			'visibility_can_see_set' => $sets['visibility_can_see_set'],
			'count_views' => $sets['count_views'],
			'count_comments' => $sets['count_comments'],
			'can_comment' => $sets['can_comment'],
			'date_create' => date('Y-m-d H:i:s',$sets['date_create']),
			'date_update' => date('Y-m-d H:i:s',$sets['date_update']),
			'videos' => $sets['videos']
		);
		
		$insertSetsResult = $wpdb->replace('flickr_sets',$insertArray);

		if(mysql_error() != ""){
			fsLog("<b>MYSQL ERROR: ".mysql_error()."</b>...<b>flickr_sets</b> 插入失败", "error");
			return array(
				'state' => false
			);
		}else{
			return array(
				'state' => true
			);
		}
	}
	
	
	/*	插入或更新 wp_posts；
	 * 	根据 set id 从 wp_meta 中检查是否已经创建 与 set 对应的 post；
	 * 	未创建->创建;
	 * 	已创建->更新;
	 * 	@param : SET set
	 * 	@return Array result
	 */
	function insertPost($set){
		global $wpdb;
		
		$result = array();
		$insertPostSaver = array();
		
		//待插入的值
		$insertArray = array(
			'post_title' => $set['title']['_content'],
			'post_content' => $set['description']['_content'],
			'post_status' => 'publish',
			'post_type' => 'post',
			'post_author' => '1',
			'post_name' => $set['title']['_content'],
			'post_parent' => 0,
			'menu_order' => 0,
			'post_date' => date('Y-m-d H:i:s',$set['date_create']),
			'post_date_gmt' => date('Y-m-d H:i:s',$set['date_create']),
			'post_excerpt' => '',
			'post_modified' => date('Y-m-d H:i:s',$set['date_update']),
			'post_modified_gmt' => date('Y-m-d H:i:s',$set['date_update']),
			'comment_count' => 0,
			'to_ping' => '',
			'pinged' => '',
			'post_content_filtered' => ''
		);
	
		/** 从 post meta 中 检查 与 set 对应的 post 是否已经创建 **/
		$hasPost = $wpdb->get_results("select `post_id` from wp_postmeta where meta_key='fsAutoPost' AND meta_value='".$set['id']."'");
		if(mysql_error() != ""){
			fsLog("<b>MYSQL ERROR: ".mysql_error()."</b>...<b>wp_postmeta</b>查询失败", "error");
			$result['state'] = false;
		}else{
			//已经创建创建 -> update
			if(count($hasPost)){
				$dbResult = $wpdb->update( $wpdb->posts,$insertArray, array(
					id => $hasPost[0]->post_id
				));
			}else{
				//没有创建 -> insert
				$dbResult = $wpdb->insert( $wpdb->posts,$insertArray);
			}
			
			if(mysql_error() != ""){
				if(count($hasPost)){
					fsLog("<b>MYSQL ERROR: ".mysql_error()."</b>... <b>wp_posts</b> 更新操作失败", "error");
				}else{
					fsLog("<b>MYSQL ERROR: ".mysql_error()."</b>... <b>wp_posts</b> 插入操作失败", "error");
				}
				$result['state'] = false;
			}else{
				//返回结果，打印日志
				if(count($hasPost)){
					if($dbResult === 0){
						fsLog("post id：<b> ".$hasPost[0]->post_id."</b> ，<b>无变更</b>", "success");
						$result['state'] = true;
					}elseif($dbResult !== false){
						fsLog("post id： <b>".$hasPost[0]->post_id."</b> ，<b>更新</b>操作成功", "success");
						$result['state'] = true;
					}else{
						$result['state'] = false;
					}
				}else{
					if($dbResult !== false){
						$insertPostSaver['post_id'] = mysql_insert_id();
						$insertPostSaver['set_id'] = $set['id'];
						fsLog("post： <b>".mysql_insert_id()."</b> ，<b>新增</b>操作成功", "success");

						$result['state'] = true;
						$result['insertPostInfo'] = $insertPostSaver;
					}else{
						$result['state'] = false;
					}
				}
				$result['state'] = true;
			}
		}
		return $result;
	}
	
	
	//insert meta
	function insertMeta($set_id,$post_id){
		global $wpdb;
		
		$insertArray = array(
			'post_id' => $post_id,
			'meta_key' => 'fsAutoPost',
			'meta_value' => $set_id
		);
		
		$insertResult = $wpdb->insert( $wpdb->postmeta,$insertArray);

		if($insertResult != false){
			return array(
				'state' => true
			);
		}else{
			return array(
				'state' => false
			);
		}
		
	}
	
	
	function resetSetTables(){
		global $wpdb;
		
		fsLog("-------------------------------------初始化开始-------------------------------------","warn",true);
		
		
		
		//empty flickr_sets
		$wpdb->query("truncate table flickr_sets");
		if(mysql_error() != ""){
			fsLog("<b>MYSQL ERROR: ".mysql_error()."</b>", "error");
		}else{
			fsLog("flickr_sets 已清空...","success");
		}

		//query post_id in postmeta
		$existsPosts = $wpdb->get_results("SELECT `post_id` FROM ".$wpdb->postmeta." WHERE `meta_key`='fsAutoPost' ");
		
		
		if(mysql_error() != ""){
			fsLog("<b>MYSQL ERROR: ".mysql_error()."</b>", "error");
		}else{
			
			// delete all fs postmeta
			/*
			$r = $wpdb->query("DELETE FROM `".$wpdb->postmeta."` WHERE `meta_key`='fsAutoPost' ");
			if(mysql_error() != ""){
				fsLog("<b>MYSQL ERROR: ".mysql_error()."</b>", "error");
			}else{
				fsLog($r." 条记录从 ".$wpdb->postmeta." 中删除...","success");
			}
			*/
				
			/*
			$deletePostCounter = 0;
			foreach ($existsPosts as $post) {
				$postId = $post->post_id;
				$deleteResult = $wpdb->query("DELETE FROM `".$wpdb->posts."` WHERE `id`=".$postId);
				if(mysql_error() != ""){
					fsLog("<b>MYSQL ERROR: ".mysql_error()."</b>", "error");
				}else{
					$deletePostCounter++;
				}
			}
			fsLog($deletePostCounter." 条记录从 ".$wpdb->posts." 中删除...","success");
			 */
		}
		

		
		fsLog("-------------------------------------初始化结束-------------------------------------","warn",true);
		
	}

	/* 检查 postmeta表中已经存在的 set ，是否存在于本次同步的 set 列表中，
	 * 如果不存在，表示该set已经从 flickr 中删除
	 * 
	 */
	function selectDeleted($setIds){
	fsLog("-------------------------------------对比set, 删除已经不存在的相关记录-------------------------------------","warn",true);
		global $wpdb;
		$result = array();
		$queryResult = $wpdb->get_results("SELECT `meta_value` set_id, `post_id` p_id FROM ".$wpdb->postmeta." WHERE `meta_key`='fsAutoPost'");
		if(mysql_error() == ""){
			while($item = array_shift($queryResult)){
				$exsit = in_array($item->set_id, $setIds);
				if($exsit){
					//存在，忽略
					continue;
				}else{
											
					//不存在，删除 postmeta 和 posts 表中相应记录
					$deletePostsResult =  removeDeleted($item->p_id);
					if($deletePostsResult['state'] == true){
						fsLog("POST: ".$item->p_id." 不存在，已从".$wpdb->posts." 和 ".$wpdb->postmeta." 中删除...","warn");
					}
					
					//删除相应的 photos
					deletePhotosBySetId($item->set_id);
				}
			}
			$result['state'] = true;
		}else{
			fsLog("<b>MYSQL ERROR: ".mysql_error()."</b>", "error");
			$result['state'] = false;
		}
		return $result;
	}

	function removeDeleted($postId){
		global $wpdb;
		$result = array();
		$rPostmeta = $wpdb->query("DELETE FROM `".$wpdb->postmeta."` WHERE `post_id`='".$postId."' ");
		$rPost = $wpdb->query("DELETE FROM `".$wpdb->posts."` WHERE `id`='".$postId."' ");
		if(mysql_error() != ""){
			fsLog("<b>MYSQL ERROR: ".mysql_error()."</b>", "error");
			$result['state'] = false;
		}else{
			$result['state'] = true;
		}
		return $result;
	}
	
?>